import { ReportAjaxError, ReportLogInfo } from './interface'

export function reportLogInfo (options:ReportLogInfo) {
  const { timeout, method, url, data = {}, params = {}, onError, onSuccess } = options
  const xhr = new XMLHttpRequest()
  let searchString = ''
  xhr.timeout = timeout || 60 * 1000
  if (method === 'GET' && params) {
    searchString += '?'
    for (const key in params) {
      if (Object.prototype.hasOwnProperty.call(params, key)) {
        searchString += `${key}=${params[key]}&`
      }
    }
    searchString = searchString.slice(0, searchString.length - 1)
  }
  xhr.open(method, url + searchString)
  xhr.onload = function onload () {
    if (xhr.status < 200 || xhr.status >= 300) {
      if (onError) {
        return onError(genError(xhr, this.responseText, method, url))
      }
    }
    if (onSuccess) {
      onSuccess(getBody(xhr))
    }
  }
  if (method === 'POST') {
    const formData = new FormData()
    Object.keys(data).forEach(key => {
      formData.append(key, data[key])
    })
    xhr.send(formData)
  } else {
    xhr.send()
  }
}

function genError (xhr:XMLHttpRequest, msg:string, method:'GET'|'POST', url:string) {
  const err = new Error(msg) as ReportAjaxError
  err.status = xhr.status
  err.method = method
  err.url = url
  return err
}

function getBody (xhr: XMLHttpRequest): XMLHttpRequestResponseType {
  const text = xhr.responseText || xhr.response
  if (!text) {
    return text
  }
  try {
    return JSON.parse(text)
  } catch (e) {
    return text
  }
}
